from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer
from django.http.request import QueryDict
from websocket.ssh import SSH
from websocket.tasks import task_add
from asset.models import *
from utils.custom_log import log_start
logger = log_start('consumer')
import os
import json
import base64
import re

# class AnsibleConsumer(AsyncWebsocketConsumer):
#     async def connect(self):
#         await self.channel_layer.group_add()
#         await self.accept()

#         query_string = self.scope.get('query_string')
#         args = QueryDict(query_string=query_string, encoding='utf-8')
#         logger.info (f"QueryDict:{args}")

#     async def disconnect(self, close_code):
#         await self.channel_layer.group_discard()
    
#     # async def receive(self, text_data=None, bytes_data=None):
#     #     await self.channel_layer.group_send()

#     async def send_message(self, event):
#         await self.send(text_data=json.dumps(event))



class AnsibleConsumer(WebsocketConsumer):
    # 当Websocket创建连接时
    def connect(self):
        ''' websocket保持连接 '''
        self.accept()  
        
        ## 获取建立ws后前端入参
        query_string = self.scope.get('query_string')
        args = QueryDict(query_string=query_string, encoding='utf-8')
        logger.info (f"QueryDict:{args}")
    
    def disconnect(self, code):
        ''' 当Websocket发生断开连接时 '''
        pass

    def receive(self, text_data=None, bytes_data=None):
        ''' 当Websocket接收到前端send消息时 '''
        print(text_data)  # 打印收到的数据
    
    def send_message(self, event):
        #自定义函数，在celery任务中使用channels_layers会用到
        self.send(text_data=json.dumps(event))

